package com.app.mingluxing.adapter;

import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewTreeObserver;
import android.view.inputmethod.InputMethodManager;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSONObject;
import com.app.mingluxing.R;
import com.app.mingluxing.bean.BabayTreeData;
import com.app.mingluxing.bean.BabyTreeComment;
import com.app.mingluxing.bean.BabyTreeCreator;
import com.app.mingluxing.bean.ResultBaseBean;
import com.app.mingluxing.fragment.HomeFragment;
import com.app.mingluxing.net.HttpUtil;
import com.app.mingluxing.ui.HomeActivity;
import com.app.mingluxing.utils.CommonUtils;
import com.app.mingluxing.utils.Constant;
import com.app.mingluxing.utils.DensityUtil;
import com.app.mingluxing.utils.LogUtil;
import com.app.mingluxing.widget.GridViewForScrollView;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.assist.ImageScaleType;
import com.nostra13.universalimageloader.core.display.SimpleBitmapDisplayer;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import cn.sharesdk.framework.Platform;
import cn.sharesdk.framework.PlatformActionListener;
import cn.sharesdk.framework.ShareSDK;
import cn.sharesdk.wechat.friends.Wechat;
import cn.sharesdk.wechat.moments.WechatMoments;

/**
 * Created by Aaron on 2015/7/24.
 */
public class HomeAdapter extends BaseAdapter {

    private Context ctx;
    private List<BabayTreeData> babayTreeDatas;
    private View fragmentView;
    private HomeActivity hActivity;
    private DisplayImageOptions options;
    private SharedPreferences sp;
    private ProgressDialog dialog;

    public HomeAdapter(Context ctx, List<BabayTreeData> babayTreeDatas) {

        this.ctx = ctx;
        this.babayTreeDatas = babayTreeDatas;
        options = new DisplayImageOptions.Builder()
                .showImageOnLoading(R.drawable.icon_default)
                .showImageForEmptyUri(R.drawable.icon_default)
                .showImageOnFail(R.drawable.icon_default)
                .resetViewBeforeLoading(true)
                .cacheOnDisk(true).cacheInMemory(true)
                .cacheOnDisc(true).imageScaleType(ImageScaleType.EXACTLY)
                .bitmapConfig(Bitmap.Config.RGB_565)
                .considerExifParams(true)
                .displayer(new SimpleBitmapDisplayer()).build();

        sp = ctx.getSharedPreferences(Constant.CONFIG, ctx.MODE_PRIVATE);
    }

    @Override
    public int getCount() {

//        LogUtil.e("TAG", "getCount" + sizes.size());
        return babayTreeDatas.size();
    }

    public void setData(List<BabayTreeData> babayTreeDatas) {
        this.babayTreeDatas = babayTreeDatas;
    }

    @Override
    public Object getItem(int position) {
        return babayTreeDatas.get(position);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    public void setFragmentView(View fragmentView) {
        this.fragmentView = fragmentView;
    }

    @Override
    public View getView(final int position, View convertView, ViewGroup parent) {
        ViewHolder viewHolder = null;

        if (convertView == null) {

            convertView = View.inflate(ctx, R.layout.item_home, null);
            viewHolder = new ViewHolder();
            viewHolder.iv_head_pic = (ImageView) convertView.findViewById(R.id.iv_head_pic);
            viewHolder.iv_share = (ImageView) convertView.findViewById(R.id.iv_share);
            viewHolder.iv_comment = (ImageView) convertView.findViewById(R.id.iv_comment);

            viewHolder.tv_name = (TextView) convertView.findViewById(R.id.tv_name);
            viewHolder.tv_content = (TextView) convertView.findViewById(R.id.tv_content);
            viewHolder.tv_loaction = (TextView) convertView.findViewById(R.id.tv_loaction);
            viewHolder.tv_time = (TextView) convertView.findViewById(R.id.tv_time);
            viewHolder.tv_delete = (TextView) convertView.findViewById(R.id.tv_delete);

            viewHolder.gv_photos = (GridViewForScrollView) convertView.findViewById(R.id.gv_photos);
            viewHolder.ll_comments = (LinearLayout) convertView.findViewById(R.id.ll_comments);

            convertView.setTag(viewHolder);

        } else {
            viewHolder = (ViewHolder) convertView.getTag();
        }

        if (babayTreeDatas.get(position) != null && babayTreeDatas.get(position).creator != null) {
            //头像
            ImageLoader.getInstance().displayImage(babayTreeDatas.get(position).creator.imgUrl, viewHolder.iv_head_pic, options);
            //  发布宝宝树的人名
            viewHolder.tv_name.setText(CommonUtils.isNull(babayTreeDatas.get(position).creator.nickName) ? "" : babayTreeDatas.get(position).creator.nickName);
            // 是否显示删除按钮

            if (sp.getString(Constant.id, "0").equals(babayTreeDatas.get(position).creator.id)
                    || Constant.POWER_ADMIN == sp.getInt(Constant.LEVEL, 0)) {
                //如果是本人发的 或者 本人是这个宝宝的管理员 则可以删除该条宝宝树消息
                viewHolder.tv_delete.setVisibility(View.VISIBLE);
            }else {
                viewHolder.tv_delete.setVisibility(View.GONE);
            }

//            viewHolder.tv_delete.setVisibility(sp.getString(Constant.id, "0")
//                    .equals(babayTreeDatas.get(position).creator.id) ? View.VISIBLE : View.GONE);

        }
        if (babayTreeDatas.get(position) != null && babayTreeDatas.get(position).tree != null) {
            ArrayList<String> list = new ArrayList<String>();

            for (int i = 0; i < babayTreeDatas.get(position).imgList.size(); i++) {
                list.add(babayTreeDatas.get(position).imgList.get(i));
            }

            ShowImageAdapter imageAdapter = new ShowImageAdapter(ctx, list);

            if (list.size() == 1) {//如果只有一张图片
                viewHolder.gv_photos.setNumColumns(1);

                LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
                viewHolder.gv_photos.setLayoutParams(lp);

            } else if (list.size() == 4) {//四张图片,显示正方形
                viewHolder.gv_photos.setNumColumns(2);
                LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(viewHolder.gv_photos.getLayoutParams());
                lp.setMargins(0, 0, DensityUtil.dip2px(ctx, 85), 0);
                viewHolder.gv_photos.setLayoutParams(lp);

            } else {
                viewHolder.gv_photos.setNumColumns(3);
                LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
                viewHolder.gv_photos.setLayoutParams(lp);
            }

            viewHolder.gv_photos.setAdapter(imageAdapter);

//            //预览图片
//            final ArrayList<String> photoLists = list;
//            viewHolder.gv_photos.setOnItemClickListener(new AdapterView.OnItemClickListener() {
//                @Override
//                public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
//                    Intent mIntent = new Intent(ctx, PreviewPhotoActivity.class);
//                    mIntent.putExtra("position", i);
//                    mIntent.putStringArrayListExtra("preUrlPhotos", photoLists);
//                    ctx.startActivity(mIntent);
//                }
//            });

            //发布内容
            viewHolder.tv_content.setText(CommonUtils.isNull(babayTreeDatas.get(position).tree.content) ? "" : babayTreeDatas.get(position).tree.content);
            //发布位置
            viewHolder.tv_loaction.setText(CommonUtils.isNull(babayTreeDatas.get(position).tree.address) ? "" : babayTreeDatas.get(position).tree.address);
            //发布时间
            viewHolder.tv_time.setText(CommonUtils.isNull(babayTreeDatas.get(position).tree.createTime) ? "" : babayTreeDatas.get(position).tree.createTime);

        }
        final LinearLayout ll_temp_comments = viewHolder.ll_comments;
        setCommentData(position, ll_temp_comments);
        viewHolder.tv_delete.setOnClickListener(new View.OnClickListener() {  //删除
            @Override
            public void onClick(View v) {

//                LogUtil.e("TAG", "删除的position====>>>>" + position);
                if (babayTreeDatas.get(position).tree != null) {
                    showDeleteDialog(position, babayTreeDatas.get(position).tree.id);
                }

            }
        });

        //分享
        viewHolder.iv_share.setOnClickListener(new View.OnClickListener() {  //分享
            @Override
            public void onClick(View v) {
                showShareDialog(babayTreeDatas.get(position).shareUrl);
            }
        });

        viewHolder.iv_comment.setOnClickListener(new View.OnClickListener() {  //评论
            @Override
            public void onClick(View v) {
                onCommentClick(position, ll_temp_comments, null, null);
            }
        });
        return convertView;
    }

    /**
     * 弹出分享的对话框
     *
     * @param url 分享的Url
     */
    private void showShareDialog(final String url) {
        dialog = new ProgressDialog(ctx);
        dialog.setCanceledOnTouchOutside(true);
        dialog.show();
        dialog.setContentView(R.layout.layout_share);
        TextView tv_wechat_circle = (TextView) dialog.findViewById(R.id.tv_wechat_circle);
        TextView tv_wechat_friend = (TextView) dialog.findViewById(R.id.tv_wechat_friend);
        //微信好友
        tv_wechat_friend.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                if (dialog != null && dialog.isShowing()) {
                    dialog.dismiss();
                }

                share(url, Wechat.NAME);

            }
        });

        //微信朋友圈
        tv_wechat_circle.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                if (dialog != null && dialog.isShowing()) {
                    dialog.dismiss();
                }

                share(url, WechatMoments.NAME);

            }
        });
    }

    /**
     * 分享
     *
     * @param url      分享的Url
     * @param platform 分享的平台
     */
    private void share(final String url, String platform) {

        Platform.ShareParams psp = new Platform.ShareParams();
        psp.setShareType(Wechat.SHARE_WEBPAGE);

//        MyApplication myApplication = (MyApplication) ctx.getApplicationContext();

        psp.setTitle(sp.getString(Constant.CURRENTCHILDNAME, "") + "的最新变化");

        psp.setText(sp.getString(Constant.CURRENTCHILDNAME, "") + "的最新变化");

        psp.setImageUrl("http://liaoning.sinaimg.cn/2014/1111/U10435P1195DT20141111220802.jpg");

        psp.setImageData(BitmapFactory.decodeResource(ctx.getResources(), R.drawable.icon_share_pic));

        psp.setUrl(url);

        Platform weChat = ShareSDK.getPlatform(platform);

        //判断wechat 是否为空

        if (weChat == null) {
            Toast.makeText(ctx, "分享失败", Toast.LENGTH_SHORT).show();
            Log.e("tag", "wechat 为空");
            return;
        }

        weChat.setPlatformActionListener(new PlatformActionListener() {
            @Override
            public void onComplete(Platform platform, int i, HashMap<String, Object> hashMap) {
//                    Toast.makeText(ctx, "分享完成", Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onError(Platform platform, int i, Throwable throwable) {
//                    Toast.makeText(ctx, "分享失败", Toast.LENGTH_SHORT).show();
                LogUtil.e("tag", "分享失败==" + throwable.getMessage());
            }

            @Override
            public void onCancel(Platform platform, int i) {

            }

        });
        weChat.share(psp);
    }

    /**
     * 删除宝宝树的对话框
     *
     * @param position 要删除的宝宝树item的位置
     * @param id       要删除宝宝树的id
     */
    private void showDeleteDialog(final int position, final String id) {
        new AlertDialog.Builder(ctx).setCancelable(true).setTitle("提示").setMessage("确定删除").setNegativeButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                dialogInterface.dismiss();
            }
        }).setPositiveButton("删除", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                dialogInterface.dismiss();
                //删除宝宝树
                deleteBabayTreeItem(position, id);
            }
        }).show();
    }

    /**
     * 删除宝宝树
     *
     * @param position 要删除的宝宝树item的位置
     * @param id       要删除宝宝树的id
     */
    private void deleteBabayTreeItem(final int position, String id) {
        BabyTreeCreator babyTreeCreator = new BabyTreeCreator();
        babyTreeCreator.token = sp.getString(Constant.TOKEN, "");
        babyTreeCreator.tid = id;
//        String requestStr = JSONObject.toJSONString(babyTreeCreator);

        HttpUtil.setPostRequest("删除中...", ctx, Constant.WEB_ROOT + Constant.DELTREE, JSONObject.toJSONString(babyTreeCreator),
                HomeFragment.class.getName(), new HttpUtil.SuccessListener() {
            @Override
            public void setOnSuccessListener(String str) {
                if (CommonUtils.isNull(str)) {
                    Toast.makeText(ctx, Constant.NODATA, Toast.LENGTH_SHORT).show();
                    return;
                }
                ResultBaseBean resultBaseBean = JSONObject.parseObject(str, ResultBaseBean.class);
                if (resultBaseBean.code == Constant.STATUS_SUCCESS) {
                    babayTreeDatas.remove(position);
                    notifyDataSetChanged();
                } else {
                    Toast.makeText(ctx, Constant.showErrorMsg(resultBaseBean.code, ctx), Toast.LENGTH_SHORT).show();
                }
            }
        }, null);
    }

    /**
     * 设置评论的数据
     *
     * @param position 当前所属的item的位置
     * @param ll       用于添加评论子view的线性布局
     */
    private void setCommentData(final int position, final LinearLayout ll) {

        List<BabyTreeComment> commentList = babayTreeDatas.get(position).comment;

        //如果没有评论数据 不需要背景
        if (commentList == null || commentList.size() == 0) {
            ll.setVisibility(View.GONE);
        }else {
            ll.setVisibility(View.VISIBLE);
        }

        //添加之前移除所有的子view
        ll.removeAllViews();
        for (int i = 0; i < commentList.size(); i++) {
            View view = View.inflate(ctx, R.layout.item_comment, null);
            //当前评论的item加入到评论的总布局中
            ll.addView(view);
            TextView tv_comment = (TextView) view.findViewById(R.id.tv_comment);//评论人的名字
            TextView tv_reply = (TextView) view.findViewById(R.id.tv_reply);//回复
            TextView tv_comment_to = (TextView) view.findViewById(R.id.tv_comment_to);//被评论人的名字
            TextView tv_comment_content = (TextView) view.findViewById(R.id.tv_comment_content);//评论内容

            //设置评论人姓名
            if (commentList.get(i).fromId != null && commentList.get(i).fromId.equals(sp.getString(Constant.id, ""))) {
                tv_comment.setText("我");
            } else {
                tv_comment.setText(CommonUtils.isNull(commentList.get(i).fromName) ? "" : commentList.get(i).fromName);
            }

            //设置评论内容
            tv_comment_content.setText(CommonUtils.isNull(commentList.get(i).content) ? "" : commentList.get(i).content);

            //判断有无被评论人
            if (CommonUtils.isNull(commentList.get(i).toId)) {   //没有被评论人

                tv_reply.setText("");
                tv_comment_to.setVisibility(View.GONE);

            } else {  //有被评论人

                tv_reply.setText("回复");
                tv_comment_to.setVisibility(View.VISIBLE);
                //看 被评论人是否是自己,如果是自己 则显示 我
                if (commentList.get(i).toId != null && commentList.get(i).toId.equals(sp.getString(Constant.id, ""))) {
                    tv_comment_to.setText("我");
                } else {
                    //被评论人不是我
                    tv_comment_to.setText(commentList.get(i).toName);
                }

                //判断评论人和被评论人是否是同一个人 如果是同一个人则显示 某人: (相当于没有被评论人)
                if (commentList.get(i).fromId != null && commentList.get(i).toId != null &&
                        commentList.get(i).toId.equals(commentList.get(i).fromId)) {

                    tv_reply.setText("");
                    tv_comment_to.setVisibility(View.GONE);

                }

            }
            final List<BabyTreeComment> tempCommentList = commentList;
            final int temp = i;
            view.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    String name = tempCommentList.get(temp).fromName;
                    String id = tempCommentList.get(temp).fromId;
                    onCommentClick(position, ll, name, id);
                }
            });
        }
    }

    /**
     * 评论的点击方法
     *
     * @param position 被评论的item的位置
     * @param ll       用于添加评论条目的线性布局
     * @param to_name     被评论人的姓名
     * @param to_id       被评论人的id
     */
    private void onCommentClick(final int position, final LinearLayout ll, final String to_name, final String to_id) {

        if (fragmentView == null)
            return;

        if (ctx instanceof HomeActivity) {
            hActivity = (HomeActivity) ctx;
        }

        if (hActivity == null)
            return;

        final RelativeLayout rl_bottom_comment = (RelativeLayout) fragmentView.findViewById(R.id.rl_bottom_comment);
        Button btn_comment = (Button) fragmentView.findViewById(R.id.btn_comment);
        final EditText et_comment = (EditText) fragmentView.findViewById(R.id.et_comment);
        rl_bottom_comment.setVisibility(View.VISIBLE);
        InputMethodManager inputManager = (InputMethodManager)
                et_comment.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
        inputManager.toggleSoftInput(0, InputMethodManager.HIDE_NOT_ALWAYS);
        et_comment.setText("");

        if (CommonUtils.isNull(to_id) || sp.getString(Constant.id, "").equals(to_id)) {//没有被评论人 , 或者被评论人是我自己
            et_comment.setHint(ctx.getResources().getString(R.string.my_comment));
        } else {
            et_comment.setHint("回复：" + to_name);
        }
        //隐藏和显示 评论输入框的监听
        fragmentView.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
            @Override
            public void onGlobalLayout() {

//                    LogUtil.e("tag", "rootHigh==>" + fragmentView.getRootView().getHeight() +
//                            ",fragmentHigh==>" + fragmentView.getHeight());

                if (fragmentView.getRootView().getHeight() - fragmentView.getHeight() < 250) {
                    //小于250说明 软键盘隐藏了
                    if (hActivity != null) {
                        //底部按钮 显示出来
                        hActivity.showButtom();
                        //评论输入框隐藏
                        rl_bottom_comment.setVisibility(View.GONE);

                    }

                } else {
                    //软键盘显示出来了
                    if (hActivity != null) {
                        //底部按钮隐藏
                        hActivity.hitButtom();
                        //输入框显示
                        rl_bottom_comment.setVisibility(View.VISIBLE);
                        et_comment.requestFocus();
                    }
                }

            }
        });

        btn_comment.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (CommonUtils.isNull(et_comment.getText().toString().trim())) {
                    Toast.makeText(ctx, "请输入评论内容", Toast.LENGTH_SHORT).show();
                    return;
                }

                if (CommonUtils.isNull(to_id) || sp.getString(Constant.id, "").equals(to_id)) //没有被评论人 , 或者被评论人是我自己
                    addComment(et_comment.getText().toString().trim(), babayTreeDatas.get(position).tree.id, position, ll, "", "");
                else
                    addComment(et_comment.getText().toString().trim(), babayTreeDatas.get(position).tree.id, position, ll, to_name, to_id);

            }
        });
    }

    /**
     * 添加评论的方法
     *
     * @param comment    评论的内容
     * @param babyTreeId 所评论的宝宝树的Id
     * @param ll         添加评论的线性布局
     * @param name       被评论人的姓名
     * @param id         被评论的人的ID
     */
    private void addComment(final String comment, final String babyTreeId, final int position, final LinearLayout ll, final String name, final String id) {

        JSONObject j = new JSONObject();
        j.put("token", sp.getString(Constant.TOKEN, ""));
        j.put("content", comment);
        j.put("tid", babyTreeId);
        j.put("to_id", CommonUtils.isNull(id) ? "" : id);
        j.put("to_name", CommonUtils.isNull(name) ? "" : name);

        HttpUtil.setPostRequest("评论中...", ctx, Constant.WEB_ROOT + Constant.SENDCOMMENT,
                j.toJSONString(), HomeFragment.class.getName(), new HttpUtil.SuccessListener() {
            @Override
            public void setOnSuccessListener(String str) {
                try {
                    ResultBaseBean resultBaseBean = JSONObject.parseObject(str, ResultBaseBean.class);
                    if (resultBaseBean.code == Constant.STATUS_SUCCESS) {
                        BabyTreeComment btc = new BabyTreeComment();
                        //评论内容
                        btc.content = comment;
//                        btc.fromName = sp.getString(Constant.NICKNAME, "我"); //评论人
                        btc.fromName = "我"; //评论人
                        //被评论人的姓名
                        btc.toName = name;
                        btc.toId = id;
                        babayTreeDatas.get(position).comment.add(btc);
                        setCommentData(position, ll);

                    } else {
                        Toast.makeText(ctx, Constant.showErrorMsg(resultBaseBean.code, ctx), Toast.LENGTH_SHORT).show();
                    }
                } catch (Exception e) {
                    Toast.makeText(ctx, Constant.NODATA, Toast.LENGTH_SHORT).show();
                }

            }
        }, null);
    }

    private class ViewHolder {
        private ImageView iv_head_pic;
        private TextView tv_name;
        private TextView tv_content;
        private GridViewForScrollView gv_photos;
        private TextView tv_loaction;
        private TextView tv_time;
        private TextView tv_delete;
        private ImageView iv_share;
        private ImageView iv_comment;
        private LinearLayout ll_comments;
    }

}
